package game_logic.view;

import game_logic.model.Board;
import game_logic.model.Piece;
import game_logic.util.Utils;

import javax.swing.*;

/**
 * 实现棋子视图接口
 */
public class SimplePieceView implements PieceView {
    @Override
    public void display(Board board) {
        for (int x = 0; x < 9; ++x) {
            for (int y = 0; y < 10; ++y) {
                Piece piece = board.getPiece(x, y);
                int[] viewPos = Utils.getViewPos(new int[]{x, y}, reverseBoard);
                if (piece == null) continue; // 如果没有棋子，那么跳过
                pieces.add(makeJLabelPiece(viewPos[0], viewPos[1], piece), JLayeredPane.MODAL_LAYER);
            }
        }
    }

    /**
     * 根据传入的信息，构造显示棋子的 JLabel
     *
     * @param x     棋子位置纵坐标
     * @param y     棋子位置横坐标
     * @param piece 棋子
     * @return 显示棋子的 JLabel
     */
    private JLabel makeJLabelPiece(int x, int y, Piece piece) {
        JLabel retJLabel = new JLabel(new ImageIcon("res/img/" + this.pictureName(piece)));
        retJLabel.setLocation(x, y);
        retJLabel.setSize(SimpleBoardView.PIECE_WIDTH, SimpleBoardView.PIECE_HEIGHT);
//        retJLabel.addMouseListener(new PieceOnClickListener(key));
//        pieceObjects.put(stringPieceEntry.getKey(), retJLabel);
        return retJLabel;
    }

    /**
     * 根据指定棋子的信息返回对应的图片名称。信息包括：棋手id，棋子类型
     *
     * @param piece 指定棋子
     * @return 对应的图片名称
     */
    private String pictureName(Piece piece) {
        StringBuilder builder = new StringBuilder();
        switch (piece.getOwner()) { // 棋手
            case 0 -> builder.append("red");
            case 1 -> builder.append("black");
        }
        switch (piece.getType()) {
            case Chariot -> builder.append("Chariot");
            case Horse -> builder.append("Horse");
            case Cannon -> builder.append("Cannon");
            case Soldier -> builder.append("Soldier");
            case Elephant -> builder.append("Elephant");
            case Guard -> builder.append("Guard");
            case King -> builder.append("King");
            default -> throw new UnsupportedOperationException("pictureName");
        }
        builder.append(".png");
        return builder.toString();
    }

    private final JLayeredPane pieces; // 棋子
    private final boolean reverseBoard; // 棋盘是否反转

    public SimplePieceView(JLayeredPane pieces, boolean reverseBoard) {
        this.pieces = pieces;
        this.reverseBoard = reverseBoard;
    }


}
